import sys
from PyQt5.QtWidgets import (QWidget, QTableWidget, QTableWidgetItem, 
                             QVBoxLayout, QHBoxLayout, QPushButton, 
                             QComboBox, QDateEdit, QTextEdit, QDialog,
                             QLabel, QMessageBox, QGroupBox, QFormLayout,
                             QSpinBox, QHeaderView, QMenu, QAction, QLineEdit)
from PyQt5.QtCore import QDate, Qt
from PyQt5.QtGui import QColor, QFont
from database import Database

class LeaveApplicationDialog(QDialog):
    """请假申请对话框"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("请假申请")
        self.setModal(True)
        self.setFixedSize(500, 550)  # 增加高度以容纳搜索框
        self.db = Database()
        self.all_employees = []
        self.filtered_employees = []
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout()
        
        # 员工选择
        group_box = QGroupBox("选择员工")
        form_layout = QFormLayout()
        
        # 搜索框
        search_layout = QHBoxLayout()
        search_label = QLabel("搜索:")
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入姓名或身份证号搜索...")
        self.search_input.textChanged.connect(self.filter_employees)
        search_layout.addWidget(search_label)
        search_layout.addWidget(self.search_input)
        form_layout.addRow(search_layout)
        
        self.employee_combo = QComboBox()
        self.load_employees()
        self.employee_combo.currentIndexChanged.connect(self.on_employee_changed)
        form_layout.addRow("选择员工*:", self.employee_combo)
        
        self.department_label = QLabel("")
        form_layout.addRow("部门:", self.department_label)
        
        group_box.setLayout(form_layout)
        layout.addWidget(group_box)
        
        # 请假信息
        group_box2 = QGroupBox("请假信息")
        form_layout2 = QFormLayout()
        
        self.leave_type_combo = QComboBox()
        self.leave_type_combo.addItems(["事假", "病假", "年假", "婚假", "产假", "其他"])
        form_layout2.addRow("请假类型*:", self.leave_type_combo)
        
        # 日期选择
        date_layout = QHBoxLayout()
        self.start_date_edit = QDateEdit()
        self.start_date_edit.setDate(QDate.currentDate())
        self.start_date_edit.setCalendarPopup(True)
        self.start_date_edit.setDisplayFormat("yyyy-MM-dd")
        date_layout.addWidget(QLabel("开始日期*:"))
        date_layout.addWidget(self.start_date_edit)
        
        self.end_date_edit = QDateEdit()
        self.end_date_edit.setDate(QDate.currentDate().addDays(1))
        self.end_date_edit.setCalendarPopup(True)
        self.end_date_edit.setDisplayFormat("yyyy-MM-dd")
        self.end_date_edit.dateChanged.connect(self.calculate_days)
        date_layout.addWidget(QLabel("结束日期*:"))
        date_layout.addWidget(self.end_date_edit)
        
        form_layout2.addRow(date_layout)
        
        self.days_label = QLabel("1 天")
        self.days_label.setStyleSheet("font-weight: bold; color: blue;")
        form_layout2.addRow("请假天数:", self.days_label)
        
        self.reason_text = QTextEdit()
        self.reason_text.setPlaceholderText("请输入请假原因...")
        self.reason_text.setMaximumHeight(100)
        form_layout2.addRow("请假原因*:", self.reason_text)
        
        group_box2.setLayout(form_layout2)
        layout.addWidget(group_box2)
        
        # 按钮
        button_layout = QHBoxLayout()
        
        submit_btn = QPushButton("提交申请")
        submit_btn.clicked.connect(self.submit_leave)
        button_layout.addWidget(submit_btn)
        
        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(cancel_btn)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
        
        # 初始计算天数
        self.calculate_days()
    
    def load_employees(self):
        """加载员工列表"""
        self.all_employees = self.db.get_all_employees()
        self.filtered_employees = self.all_employees
        self.update_employee_combo()
    
    def filter_employees(self):
        """根据搜索条件过滤员工"""
        search_text = self.search_input.text().strip().lower()
        
        if not search_text:
            self.filtered_employees = self.all_employees
        else:
            self.filtered_employees = [
                emp for emp in self.all_employees
                if (search_text in str(emp[1]).lower() or  # 姓名
                    search_text in str(emp[3]).lower())    # 身份证号
            ]
        
        self.update_employee_combo()
    
    def update_employee_combo(self):
        """更新员工下拉框"""
        current_index = self.employee_combo.currentIndex()
        current_data = self.employee_combo.currentData() if current_index >= 0 else None
        
        self.employee_combo.clear()
        
        for emp in self.filtered_employees:
            # 显示格式: 姓名 (身份证号后4位)
            id_card = str(emp[3])
            display_text = f"{emp[1]} ({id_card[-4:]})" if len(id_card) >= 4 else f"{emp[1]}"
            self.employee_combo.addItem(display_text, emp[0])
        
        # 尝试恢复之前的选择
        if current_data:
            for i in range(self.employee_combo.count()):
                if self.employee_combo.itemData(i) == current_data:
                    self.employee_combo.setCurrentIndex(i)
                    break
        
        # 如果没有匹配项，显示提示
        if not self.filtered_employees:
            self.employee_combo.addItem("无匹配员工", -1)
            self.department_label.setText("")
    
    def on_employee_changed(self, index):
        """员工选择变化时更新部门信息"""
        if index >= 0 and self.filtered_employees:
            employee_id = self.employee_combo.itemData(index)
            if employee_id != -1:  # 不是"无匹配员工"项
                employee = self.db.get_employee_by_id(employee_id)
                if employee:
                    self.department_label.setText(employee[9])
                else:
                    self.department_label.setText("")
            else:
                self.department_label.setText("")
    
    def calculate_days(self):
        """计算请假天数"""
        start_date = self.start_date_edit.date()
        end_date = self.end_date_edit.date()
        days = start_date.daysTo(end_date) + 1
        self.days_label.setText(f"{days} 天")
        return days
    
    def validate_input(self):
        """验证输入数据"""
        if self.employee_combo.currentIndex() < 0 or self.employee_combo.currentData() == -1:
            QMessageBox.warning(self, "警告", "请选择有效的员工！")
            return False
        
        if not self.reason_text.toPlainText().strip():
            QMessageBox.warning(self, "警告", "请输入请假原因！")
            return False
        
        if self.start_date_edit.date() > self.end_date_edit.date():
            QMessageBox.warning(self, "警告", "开始日期不能晚于结束日期！")
            return False
        
        return True
    
    def submit_leave(self):
        """提交请假申请"""
        try:
            if not self.validate_input():
                return
            
            employee_id = self.employee_combo.currentData()
            employee = self.db.get_employee_by_id(employee_id)
            
            if not employee:
                QMessageBox.critical(self, "错误", "选择的员工不存在！")
                return
            
            days = self.calculate_days()
            
            leave_data = (
                employee_id,
                employee[1],
                employee[9],
                self.leave_type_combo.currentText(),
                self.start_date_edit.date().toString("yyyy-MM-dd"),
                self.end_date_edit.date().toString("yyyy-MM-dd"),
                days,
                self.reason_text.toPlainText().strip()
            )
            
            success = self.db.add_leave(leave_data)
            if success:
                QMessageBox.information(self, "成功", "请假申请提交成功！")
                self.accept()
            else:
                QMessageBox.critical(self, "错误", "请假申请提交失败！")
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"提交请假申请时发生异常：{str(e)}")

class LeaveManager(QWidget):
    def __init__(self, user_role="admin"):
        super().__init__()
        self.db = Database()
        self.user_role = user_role
        self.init_ui()
        self.load_leaves()
    
    def init_ui(self):
        layout = QVBoxLayout()
        
        # 操作按钮
        btn_layout = QHBoxLayout()
        
        apply_btn = QPushButton("➕ 申请请假")
        apply_btn.clicked.connect(self.apply_leave)
        apply_btn.setStyleSheet("QPushButton { padding: 8px; font-weight: bold; }")
        btn_layout.addWidget(apply_btn)
        
        if self.user_role in ["manager", "admin"]:
            approve_btn = QPushButton("✅ 审批管理")
            approve_btn.clicked.connect(self.manage_approvals)
            approve_btn.setStyleSheet("QPushButton { padding: 8px; font-weight: bold; }")
            btn_layout.addWidget(approve_btn)
            
            # 添加批量删除按钮（仅管理员）
            self.batch_delete_btn = QPushButton("批量删除")
            self.batch_delete_btn.clicked.connect(self.batch_delete_leaves)
            self.batch_delete_btn.setEnabled(False)
            self.batch_delete_btn.setStyleSheet("QPushButton { padding: 8px; background-color: #ff6b6b; color: white; }")
            btn_layout.addWidget(self.batch_delete_btn)
        
        stats_btn = QPushButton("📊📊 统计查看")
        stats_btn.clicked.connect(self.show_stats)
        stats_btn.setStyleSheet("QPushButton { padding: 8px; font-weight: bold; }")
        btn_layout.addWidget(stats_btn)
        
        refresh_btn = QPushButton("🔄🔄 刷新")
        refresh_btn.clicked.connect(self.load_leaves)
        refresh_btn.setStyleSheet("QPushButton { padding: 8px; }")
        btn_layout.addWidget(refresh_btn)
        
        layout.addLayout(btn_layout)
        
        # 请假表格
        self.table = QTableWidget()
        self.table.setColumnCount(11)  # 增加选择列
        headers = ["选择", "序号", "员工姓名", "部门", "请假类型", "开始日期", "结束日期", 
                  "天数", "原因", "状态", "操作"]
        self.table.setHorizontalHeaderLabels(headers)
        
        # 设置列宽
        self.table.setColumnWidth(0, 50)    # 选择列
        self.table.setColumnWidth(1, 50)    # 序号
        self.table.setColumnWidth(2, 100)   # 员工姓名
        self.table.setColumnWidth(3, 100)   # 部门
        self.table.setColumnWidth(4, 80)    # 请假类型
        self.table.setColumnWidth(5, 100)   # 开始日期
        self.table.setColumnWidth(6, 100)   # 结束日期
        self.table.setColumnWidth(7, 60)    # 天数
        self.table.setColumnWidth(8, 200)   # 原因
        self.table.setColumnWidth(9, 80)    # 状态
        self.table.setColumnWidth(10, 150)  # 操作
        
        # 设置单选模式，使用复选框选择
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setSelectionMode(QTableWidget.SingleSelection)
        
        # 连接复选框变化信号
        self.table.cellChanged.connect(self.on_cell_changed)
        
        # 启用右键菜单
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.table.customContextMenuRequested.connect(self.show_context_menu)
        
        # 设置表格样式
        self.table.setAlternatingRowColors(True)
        self.table.setStyleSheet("""
            QTableWidget {
                gridline-color: #d0d0d0;
                font-size: 10pt;
                alternate-background-color: #f8f8f8;
            }
            QTableWidget::item:selected {
                background-color: #b0d0ff;
            }
        """)
        
        layout.addWidget(self.table)
        self.setLayout(layout)
    
    def on_cell_changed(self, row, column):
        """复选框状态变化时更新批量删除按钮"""
        if column == 0:  # 只处理选择列的变化
            self.update_batch_delete_button()
    
    def update_batch_delete_button(self):
        """更新批量删除按钮状态"""
        if hasattr(self, 'batch_delete_btn'):
            selected_count = self.get_selected_count()
            self.batch_delete_btn.setEnabled(selected_count > 0)
            self.batch_delete_btn.setText(f"批量删除 ({selected_count})")
    
    def get_selected_count(self):
        """获取选中的记录数量"""
        count = 0
        for row in range(self.table.rowCount()):
            checkbox_item = self.table.item(row, 0)
            if checkbox_item and checkbox_item.checkState() == Qt.Checked:
                count += 1
        return count
    
    def get_selected_leave_ids(self):
        """获取选中的请假ID列表"""
        leave_ids = []
        leaves = self.db.get_all_leaves()
        
        for row in range(self.table.rowCount()):
            checkbox_item = self.table.item(row, 0)
            if checkbox_item and checkbox_item.checkState() == Qt.Checked:
                if row < len(leaves):
                    leave_ids.append(leaves[row][0])
        
        return leave_ids
    
    def batch_delete_leaves(self):
        """批量删除请假记录"""
        try:
            if self.user_role not in ["manager", "admin"]:
                QMessageBox.warning(self, "权限不足", "只有管理员可以执行批量删除操作！")
                return
            
            leave_ids = self.get_selected_leave_ids()
            
            if not leave_ids:
                QMessageBox.warning(self, "警告", "请先选择要删除的请假记录！")
                return
            
            # 确认对话框
            reply = QMessageBox.question(
                self, "确认批量删除",
                f"确定要删除选中的 {len(leave_ids)} 条请假记录吗？\n此操作不可恢复！",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                success = self.db.batch_delete_leaves(leave_ids)
                if success:
                    QMessageBox.information(self, "成功", f"成功删除 {len(leave_ids)} 条请假记录")
                    self.load_leaves()
                else:
                    QMessageBox.critical(self, "错误", "批量删除请假记录失败")
                    
        except Exception as e:
            QMessageBox.critical(self, "错误", f"批量删除失败：{str(e)}")
    
    def show_context_menu(self, position):
        """显示右键菜单"""
        row = self.table.rowAt(position.y())
        if row >= 0:
            menu = QMenu()
            
            # 获取选中行的请假ID和状态
            status_item = self.table.item(row, 9)
            
            if status_item:
                # 需要从数据库查询实际的请假ID
                leaves = self.db.get_all_leaves()
                if row < len(leaves):
                    leave_id = leaves[row][0]  # 获取实际的数据库ID
                    status = status_item.text()
                    
                    # 删除操作（管理员权限）
                    if self.user_role in ["manager", "admin"]:
                        delete_action = QAction("🗑🗑️ 删除请假记录", self)
                        delete_action.triggered.connect(lambda: self.delete_leave(leave_id))
                        menu.addAction(delete_action)
                    
                    # 查看详情
                    view_action = QAction("👁👁️ 查看详情", self)
                    view_action.triggered.connect(lambda: self.view_leave_details(row))
                    menu.addAction(view_action)
                    
                    menu.exec_(self.table.viewport().mapToGlobal(position))
    
    def delete_leave(self, leave_id):
        """删除请假记录"""
        reply = QMessageBox.question(
            self, "确认删除",
            "确定要删除这条请假记录吗？此操作不可恢复！",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            try:
                success = self.db.execute_update("DELETE FROM leaves WHERE id = ?", (leave_id,))
                if success:
                    QMessageBox.information(self, "成功", "请假记录已删除")
                    self.load_leaves()
                else:
                    QMessageBox.critical(self, "错误", "删除请假记录失败")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除失败：{str(e)}")
    
    def view_leave_details(self, row):
        """查看请假详情"""
        details = []
        for col in range(self.table.columnCount()):
            item = self.table.item(row, col)
            if item:
                details.append(f"{self.table.horizontalHeaderItem(col).text()}: {item.text()}")
        
        QMessageBox.information(self, "请假详情", "\n".join(details))
    
    def apply_leave(self):
        """申请请假"""
        dialog = LeaveApplicationDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            self.load_leaves()
    
    def load_leaves(self):
        """加载请假记录"""
        try:
            leaves = self.db.get_all_leaves()
            
            # 断开信号连接，避免触发多次
            self.table.cellChanged.disconnect(self.on_cell_changed)
            
            self.table.setRowCount(len(leaves))
            for row, leave in enumerate(leaves):
                # 选择列 - 复选框
                checkbox_item = QTableWidgetItem()
                checkbox_item.setCheckState(Qt.Unchecked)
                checkbox_item.setTextAlignment(Qt.AlignCenter)
                checkbox_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                self.table.setItem(row, 0, checkbox_item)
                
                # 序号列
                seq_item = QTableWidgetItem(str(row + 1))
                seq_item.setTextAlignment(Qt.AlignCenter)
                seq_item.setBackground(QColor(240, 240, 240))
                seq_item.setFont(QFont("Arial", 9, QFont.Bold))
                # 设置不可编辑
                seq_item.setFlags(seq_item.flags() & ~Qt.ItemIsEditable)
                self.table.setItem(row, 1, seq_item)
                
                # 其他数据列
                fields_to_display = [
                    leave[2],       # 员工姓名
                    leave[3],       # 部门
                    leave[4],       # 请假类型
                    leave[5],       # 开始日期
                    leave[6],       # 结束日期
                    leave[7],       # 天数
                    leave[8],       # 原因
                    leave[9]        # 状态
                ]
                
                for col, value in enumerate(fields_to_display, 2):
                    display_value = str(value) if value is not None else ""
                    item = QTableWidgetItem(display_value)
                    
                    # 设置不可编辑
                    item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                    
                    # 设置天数列的特殊样式
                    if col == 7:  # 天数列
                        item.setBackground(QColor(230, 240, 255))
                        item.setFont(QFont("Arial", 10, QFont.Bold))
                        item.setTextAlignment(Qt.AlignCenter)
                    
                    # 设置状态列的颜色和中文显示
                    if col == 9:  # 状态列
                        status_text = str(value).lower()
                        if status_text == "approved":
                            item.setText("已批准")
                            item.setForeground(QColor(0, 128, 0))  # 绿色
                        elif status_text == "rejected":
                            item.setText("已拒绝")
                            item.setForeground(QColor(255, 0, 0))  # 红色
                        elif status_text == "pending":
                            item.setText("待审批")
                            item.setForeground(QColor(255, 165, 0))  # 橙色
                        else:
                            item.setText("未知状态")
                        item.setTextAlignment(Qt.AlignCenter)
                    
                    self.table.setItem(row, col, item)
                
                # 操作列
                status = str(leave[9]).lower()
                if status == "pending" and self.user_role in ["manager", "admin"]:
                    btn_widget = QWidget()
                    btn_layout = QHBoxLayout()
                    btn_layout.setContentsMargins(5, 2, 5, 2)
                    btn_layout.setSpacing(5)
                    
                    approve_btn = QPushButton("批准")
                    approve_btn.setFixedSize(50, 25)
                    approve_btn.setStyleSheet("""
                        QPushButton { 
                            background-color: #4CAF50; 
                            color: white; 
                            border: none;
                            border-radius: 3px;
                            font-size: 9pt;
                        }
                        QPushButton:hover {
                            background-color: #45a049;
                        }
                    """)
                    approve_btn.clicked.connect(lambda checked, id=leave[0]: self.approve_leave(id, "approved"))
                    
                    reject_btn = QPushButton("拒绝")
                    reject_btn.setFixedSize(50, 25)
                    reject_btn.setStyleSheet("""
                        QPushButton { 
                            background-color: #f44336; 
                            color: white; 
                            border: none;
                            border-radius: 3px;
                            font-size: 9pt;
                        }
                        QPushButton:hover {
                            background-color: #da190b;
                        }
                    """)
                    reject_btn.clicked.connect(lambda checked, id=leave[0]: self.approve_leave(id, "rejected"))
                    
                    btn_layout.addWidget(approve_btn)
                    btn_layout.addWidget(reject_btn)
                    btn_widget.setLayout(btn_layout)
                    
                    # 清除旧的单元格组件
                    if self.table.cellWidget(row, 10):
                        self.table.removeCellWidget(row, 10)
                    
                    self.table.setCellWidget(row, 10, btn_widget)
                else:
                    # 清除旧的单元格组件
                    if self.table.cellWidget(row, 10):
                        self.table.removeCellWidget(row, 10)
                    
                    # 显示中文状态文本
                    status_text = "无操作"
                    if status == "approved":
                        status_text = "已批准"
                    elif status == "rejected":
                        status_text = "已拒绝"
                    elif status == "pending":
                        status_text = "待审批"
                    
                    item = QTableWidgetItem(status_text)
                    item.setTextAlignment(Qt.AlignCenter)
                    self.table.setItem(row, 10, item)
            
            # 重新连接信号
            self.table.cellChanged.connect(self.on_cell_changed)
            
            # 调整列宽
            self.table.horizontalHeader().setSectionResizeMode(8, QHeaderView.Stretch)
            
            # 更新批量删除按钮状态
            self.update_batch_delete_button()
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载请假记录失败：{str(e)}")
    
    def approve_leave(self, leave_id, status):
        """审批请假"""
        try:
            success = self.db.update_leave_status(leave_id, status, "管理员")
            if success:
                QMessageBox.information(self, "成功", f"请假已{'批准' if status == 'approved' else '拒绝'}")
                self.load_leaves()
            else:
                QMessageBox.critical(self, "错误", "操作失败，请重试")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"操作失败：{str(e)}")
    
    def manage_approvals(self):
        """审批管理 - 筛选显示待审批记录"""
        try:
            pending_leaves = self.db.execute_query(
                "SELECT * FROM leaves WHERE status = 'pending' ORDER BY created_time DESC"
            )
            
            if not pending_leaves:
                QMessageBox.information(self, "审批管理", "当前没有待审批的请假申请")
                return
            
            # 断开信号连接
            self.table.cellChanged.disconnect(self.on_cell_changed)
            
            self.table.setRowCount(len(pending_leaves))
            for row, leave in enumerate(pending_leaves):
                # 选择列 - 复选框
                checkbox_item = QTableWidgetItem()
                checkbox_item.setCheckState(Qt.Unchecked)
                checkbox_item.setTextAlignment(Qt.AlignCenter)
                checkbox_item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                self.table.setItem(row, 0, checkbox_item)
                
                # 序号列
                seq_item = QTableWidgetItem(str(row + 1))
                seq_item.setTextAlignment(Qt.AlignCenter)
                seq_item.setBackground(QColor(240, 240, 240))
                seq_item.setFont(QFont("Arial", 9, QFont.Bold))
                seq_item.setFlags(seq_item.flags() & ~Qt.ItemIsEditable)
                self.table.setItem(row, 1, seq_item)
                
                # 其他数据列
                fields_to_display = [
                    leave[2], leave[3], leave[4], 
                    leave[5], leave[6], leave[7], leave[8], "待审批"  # 强制显示中文状态
                ]
                
                for col, value in enumerate(fields_to_display, 2):
                    display_value = str(value) if value is not None else ""
                    item = QTableWidgetItem(display_value)
                    
                    # 设置不可编辑
                    item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                    
                    if col == 7:  # 天数列
                        item.setBackground(QColor(230, 240, 255))
                        item.setFont(QFont("Arial", 10, QFont.Bold))
                    
                    # 状态列显示中文
                    if col == 9:
                        item.setForeground(QColor(255, 165, 0))  # 橙色
                        item.setTextAlignment(Qt.AlignCenter)
                    
                    self.table.setItem(row, col, item)
                
                # 添加审批按钮
                btn_widget = QWidget()
                btn_layout = QHBoxLayout()
                btn_layout.setContentsMargins(5, 2, 5, 2)
                btn_layout.setSpacing(5)
                
                approve_btn = QPushButton("批准")
                approve_btn.setFixedSize(50, 25)
                approve_btn.setStyleSheet("""
                    QPushButton { 
                        background-color: #4CAF50; 
                        color: white; 
                        border: none;
                        border-radius: 3px;
                        font-size: 9pt;
                    }
                    QPushButton:hover {
                        background-color: #45a049;
                    }
                """)
                approve_btn.clicked.connect(lambda checked, id=leave[0]: self.approve_leave(id, "approved"))
                
                reject_btn = QPushButton("拒绝")
                reject_btn.setFixedSize(50, 25)
                reject_btn.setStyleSheet("""
                    QPushButton { 
                        background-color: #f44336; 
                        color: white; 
                        border: none;
                        border-radius: 3px;
                        font-size: 9pt;
                    }
                    QPushButton:hover {
                        background-color: #da190b;
                    }
                """)
                reject_btn.clicked.connect(lambda checked, id=leave[0]: self.approve_leave(id, "rejected"))
                
                btn_layout.addWidget(approve_btn)
                btn_layout.addWidget(reject_btn)
                btn_widget.setLayout(btn_layout)
                
                # 清除旧的单元格组件
                if self.table.cellWidget(row, 10):
                    self.table.removeCellWidget(row, 10)
                
                self.table.setCellWidget(row, 10, btn_widget)
            
            # 重新连接信号
            self.table.cellChanged.connect(self.on_cell_changed)
            
            # 更新批量删除按钮状态
            self.update_batch_delete_button()
            
            QMessageBox.information(self, "审批管理", f"显示 {len(pending_leaves)} 条待审批记录")
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载待审批记录失败：{str(e)}")
    
    def show_stats(self):
        """显示统计信息"""
        try:
            stats = self.db.get_leave_stats()
            
            if not stats:
                QMessageBox.information(self, "统计信息", "暂无请假统计数据")
                return
            
            message = "📊📊 请假统计汇总\n\n"
            total_count = 0
            total_days = 0
            
            for stat in stats:
                message += f"• {stat[0]} - {stat[1]} - {stat[2]}: {stat[3]}次, 共{stat[4]}天\n"
                total_count += stat[3]
                total_days += stat[4] if stat[4] else 0
            
            message += f"\n📈📈 总计: {total_count}次请假, 共{total_days}天"
            
            # 添加各状态统计（中文显示）
            status_stats = self.db.execute_query(
                "SELECT status, COUNT(*), SUM(days) FROM leaves GROUP BY status"
            )
            message += "\n\n🔍🔍 状态分布:\n"
            for stat in status_stats:
                status_map = {"pending": "待审批", "approved": "已批准", "rejected": "已拒绝"}
                status_text = status_map.get(stat[0], stat[0])
                message += f"• {status_text}: {stat[1]}次, {stat[2] or 0}天\n"
            
            QMessageBox.information(self, "统计信息", message)
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"获取统计信息失败：{str(e)}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = LeaveManager()
    window.show()
    sys.exit(app.exec_())